import React, { useState, createElement, useEffect, Suspense } from "react";
import { Layout, Menu } from "antd";
import {
  MenuUnfoldOutlined,
  MenuFoldOutlined,
  UserOutlined,
} from "@ant-design/icons";
import "./App.less";
import { Switch, Route, Redirect, Link, useHistory } from "react-router-dom";
import { Dashboard, User, Global, Service } from "./router";

const { SubMenu } = Menu;

const { Header, Sider, Content } = Layout;

const PathMap = {
  "/dashboard": "dashboard",
  "/global": "全局服务",
  "/service": "监控服务",
  "/user": "用户行为",
};

function App() {
  const [collapsed, setCollapsed] = useState(false);
  const [currentTab, setCurrentTab] = useState(PathMap["/dashboard"]);
  const history = useHistory();
  let historyListen = history.listen((e) => {
    setCurrentTab(PathMap[e.pathname]);
  });
  const toggle = () => {
    setCollapsed(!collapsed);
  };

  useEffect(() => {
    return () => {
      historyListen && historyListen();
    };
  });
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Layout className="app-layout">
        <Sider trigger={null} collapsible collapsed={collapsed}>
          <div className="logo">#900#</div>
          <Menu
            theme="dark"
            mode="inline"
            defaultSelectedKeys={["dashboard"]}
            defaultOpenKeys={["sub1"]}
          >
            <Menu.Item key="dashboard" icon={<UserOutlined />}>
              <Link to="/dashboard">Dashboard</Link>
            </Menu.Item>
            <SubMenu key="sub1" icon={<UserOutlined />} title="监控页">
              <Menu.Item key="global">
                <Link to="/global">全局监控</Link>
              </Menu.Item>
              <Menu.Item key="service">
                <Link to="/service">服务监控</Link>
              </Menu.Item>
              <Menu.Item key="user">
                <Link to="/user">用户行为</Link>
              </Menu.Item>
            </SubMenu>
          </Menu>
        </Sider>
        <Layout className="site-layout">
          <Header className="site-layout-background" style={{ padding: 0 }}>
            {createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
              className: "trigger",
              onClick: toggle,
            })}
            {currentTab}
          </Header>
          <Content
            className="site-layout-background"
            style={{
              margin: "24px 16px",
              padding: 24,
              minHeight: 280,
            }}
          >
            <Switch>
              <Route path="/dashboard" exact component={Dashboard} />
              <Route path="/global" exact component={Global} />
              <Route path="/service" exact component={Service} />
              <Route path="/user" exact component={User} />
              <Redirect to="/dashboard" />
            </Switch>
          </Content>
        </Layout>
      </Layout>
    </Suspense>
  );
}

export default App;
